package com.w.picture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.w.picture.api.aliyunai.AliYunAiApi;
import com.w.picture.api.aliyunai.model.ImageOutPaintingRequest;
import com.w.picture.api.aliyunai.model.ImageOutPaintingResponse;
import com.w.picture.exception.BusinessException;
import com.w.picture.exception.ErrorCode;
import com.w.picture.exception.ThrowUtils;
import com.w.picture.manager.CosManager;
import com.w.picture.manager.upload.FilePictureUpload;
import com.w.picture.manager.upload.PictureUploadTemplate;
import com.w.picture.manager.upload.UrlPictureUpload;
import com.w.picture.mapper.PictureMapper;
import com.w.picture.mode.dto.file.UploadPictureResult;
import com.w.picture.mode.dto.picture.*;
import com.w.picture.mode.entity.Picture;
import com.w.picture.mode.entity.Space;
import com.w.picture.mode.entity.User;
import com.w.picture.mode.enums.FileUploadBizEnum;
import com.w.picture.mode.enums.PictureReviewStatusEnum;
import com.w.picture.mode.vo.PictureVO;
import com.w.picture.mode.vo.UserVo;
import com.w.picture.service.PictureService;
import com.w.picture.service.SpaceService;
import com.w.picture.service.UserService;
import com.w.picture.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author wzp
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-31 11:45:13
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private UserService userService;
    @Resource
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 上传图片
     * 所有图片都放在public下，每个用户的用户id 作为目录
     * 如果pictureId 不为空，表示更新图片，否则是新增图片
     *
     * @param inputSource          输入源
     * @param pictureUploadRequest 图片上传请求信息
     * @param loginUser            登录用户
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, String type, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "图片为空");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        // 空间权限校验
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            // 必须空间创建人（管理员）才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有空间权限");
//            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "空间大小不足");
            }
        }

        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
//            // 仅本人或管理员可编辑
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "空间 id 不一致");
                }
            }
        }

        // 上传图片，得到信息
        // 按照用户 id 和业务场景划分目录  => 调整为按照空间划分
        String uploadPathPrefix;
        if (spaceId == null) {
            // 公共图片
            uploadPathPrefix = String.format("%s/%s", FileUploadBizEnum.PUBLIC_IMAGE.getUploadPathPrefix(), loginUser.getId());
        } else {
            // 空间图片
            uploadPathPrefix = String.format("%s/%s", FileUploadBizEnum.SPACE_IMAGE.getUploadPathPrefix(), spaceId);
        }


        // 根据输入源类型，选择对应的上传方式,,当然这里还可以通过传入而外的参数type来区分调用的是文件上传还是url上传，或者通过策略模式配合选则上传方式。
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String || type.equals("url")) {
            pictureUploadTemplate = urlPictureUpload;
        }

        // 上传图片，得到信息
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix, FileUploadBizEnum.PUBLIC_IMAGE);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId);// 指定空间ID
        picture.setUrl(uploadPictureResult.getUrl()); // 压缩图地址
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl()); // 缩略图地址
        picture.setOriginalUrl(uploadPictureResult.getOriginalUrl()); // 原图地址
        picture.setHost(uploadPictureResult.getHost()); //  对象存储域名
        // 如果 传入的 图片名称不为空 就用传入的
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());

        // 填充审核参数
        this.fillReviewParams(picture, loginUser);

        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }

        // 填充图片主色调
        picture.setPicColor(uploadPictureResult.getPicColor());

        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        boolean asc = pictureQueryRequest.getSortOrder().equals("asc");
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();

        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件 模糊搜索图片名称和简介
            queryWrapper.and(qw -> qw.like("name", searchText).or().like("introduction", searchText));
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            // 由于 tags 是 JSON 数组,如果前端传多个 tag,必须同时存在才查询出来，所以需要循环拼接 and 条件
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), asc, sortField);
        // 增加和审核相关的条件查询语句
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);

        // 增加和编辑时间相关的条件查询语句
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVO pictureVO = PictureVO.objToVo(picture);
        if (pictureVO != null && pictureVO.getUserId() != null && pictureVO.getUserId() > 0) {
            // 获取用户信息
            User user = userService.getById(pictureVO.getUserId());
            UserVo userVo = userService.getUserVo(user);
            pictureVO.setUser(userVo);
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        if (picturePage == null) {
            return null;
        }
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息 这里直接批量查询用户数据，降低数据库的访问次数
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVo(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR, "请求不能为空");
        Long id = pictureReviewRequest.getId();
        PictureReviewStatusEnum enumByValue = PictureReviewStatusEnum.getEnumByValue(pictureReviewRequest.getReviewStatus());
        // id == null 状态 == null 状态 == 待审核 异常,因为默认图片就是待审核
        ThrowUtils.throwIf(id == null || enumByValue == null || PictureReviewStatusEnum.REVIEWING.equals(enumByValue), ErrorCode.PARAMS_ERROR);
        // 判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 已经是该状态
        ThrowUtils.throwIf(oldPicture.getReviewStatus().equals(enumByValue.getValue()), ErrorCode.PARAMS_ERROR, "请勿重复审核");
        // 更新审核状态
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库
            if (userService.isAdmin(loginUser)) {
                //管理员自动过审图片
                picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
                picture.setReviewerId(loginUser.getId());
                picture.setReviewTime(new Date());
                picture.setReviewMessage("管理员自动过审");
            } else {
                // 非管理员,创建和编辑图片都需要审核图片
                picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
            }
        } else {
            //私有空间,图片暂时默认通过,团队空间
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("私有图片/团队空间默认通过");
        }

    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest request, User loginUser) throws UnsupportedEncodingException {
        // 检查并设置参数
        String searchText = request.getSearchText();
        int count = request.getCount() == null ? 0 : request.getCount();
        ThrowUtils.throwIf(count <= 0 || count > 30, ErrorCode.PARAMS_ERROR, "一次最多30条");

        String namePrefix = StrUtil.isNotBlank(request.getNamePrefix()) ? request.getNamePrefix() : searchText;

        // 构造抓取URL
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&first=0&count=%d&mmasync=1", URLEncoder.encode(searchText, "UTF-8"), count);

        Document document;
        try {

            // 发送HTTP请求获取文档
            document = Jsoup.connect(fetchUrl).userAgent("Mozilla") // 设置User-Agent避免被识别为爬虫
                    .timeout(10 * 1000)   // 设置超时时间
                    .get();
        } catch (IOException e) {
            log.error("抓取图片失败: {}", fetchUrl, e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "图片抓取失败");
        }

        // 这里的选择器 ".dgControl img.mimg" 包含了两个部分：
        // 1. ".dgControl"：点符号表示我们正在寻找拥有名为 "dgControl" 的 CSS 类class的元素。这通常用于标识页面上的某个区域或组件。
        // 2. "img.mimg"：这部分指定了我们要查找的是 <img> 标签，并且这些标签必须同时拥有名为 "mimg" 的 CSS 类class。
        //
        // 当这两个部分组合在一起时（即 ".dgControl img.mimg"），意味着我们将只选择那些位于拥有 "dgControl" 类的父级元素之内的、并且自己也带有 "mimg" 类的 <img> 标签。
        //
        // 返回的结果是一个 Elements 对象，它实际上是一个 Element 对象的列表，每个 Element 都代表一个匹配的选择器的 HTML 元素。
        Elements imgElements = document.select(".dgControl img.mimg");
        if (imgElements.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "没有找到图片");
        }

        List<String> urlList = imgElements.stream().map(e -> e.attr("src")).filter(StrUtil::isNotBlank).collect(Collectors.toList());

        if (urlList.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "有效的图片链接为空");
        }

        log.info("成功抓取图片链接数量: {}", urlList.size());

        // 使用并发流处理图片上传以提高效率
        AtomicInteger successCount = new AtomicInteger();
        urlList.parallelStream().forEach(url -> {
            try {
                // 处理图片链接中的查询参数
                int questionMarkIndex = url.indexOf("?");
                String cleanUrl = questionMarkIndex > -1 ? url.substring(0, questionMarkIndex) : url;

                // 准备上传请求
                PictureUploadRequest uploadRequest = new PictureUploadRequest();
                uploadRequest.setPicName(namePrefix + "_" + (successCount.incrementAndGet()));

                // 执行上传操作
                PictureVO uploadedPicture = this.uploadPicture(cleanUrl, "url", uploadRequest, loginUser);
                log.info("图片上传成功, id: {}", uploadedPicture.getId());
            } catch (Exception e) {
                log.error("图片上传失败: {}", url, e);
            }
        });

        return successCount.get();
    }

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        try {
            // 判断该图片是否被多条记录使用
            String pictureUrl = oldPicture.getUrl();
            long count = this.lambdaQuery()
                    .eq(Picture::getUrl, pictureUrl)
                    .count();
            // 有不止一条记录用到了该图片，不清理
            if (count > 1) {
                return;
            }
            // FIXME 注意，这里的 url 不能包含了域名，实际上只要传 key 值（存储路径）就够了
            String url = oldPicture.getUrl();
            List<String> keys = new ArrayList<>();
            if (StrUtil.isNotBlank(url)) {
                keys.add(url);
            }
            String thumbnailUrl = oldPicture.getThumbnailUrl();
            // 清理缩略图
            if (StrUtil.isNotBlank(thumbnailUrl) && !thumbnailUrl.equals(url)) {
                keys.add(thumbnailUrl);
            }
            String originalUrl = oldPicture.getOriginalUrl();
            // 清理原图
            if (StrUtil.isNotBlank(originalUrl) && !url.equals(originalUrl)) {
                keys.add(originalUrl);
            }
            if (!keys.isEmpty()) {
                cosManager.deleteObject(keys);
            }
        } catch (Exception e) {
            log.error("清理图片文件失败", e);
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        // 已经修改为,使用Sa-Token注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);

    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
//        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        // 已经修改为,使用Sa-Token注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有空间权限");
        }
        // 3.查询该空间下所有图片(必须有主色调),有才能进行相似度匹配
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果一张符合要求的图片都没有,直接返回空列表
        if (CollectionUtils.isEmpty(pictureList)) {
            return new ArrayList<>();
        }

        // 将目标颜色转换为Color对象
        Color targetColor = Color.decode("0x" + picColor.replaceFirst("^(#|0x)", ""));
        // 4.通过工具类计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片,直接返回最大值,排最后面
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_EXPONENT;
                    }
                    Color color = Color.decode("0x" + hexColor.replaceFirst("^(#|0x)", ""));
                    // 计算相似度  (取反，使得相似度越高的图片得到更低的数值,Comparator.comparingDouble 默认是升序排列的，也就是说它会将较小的数值排在前面)
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, color);
                }))
                // 反转比较器以实现降序排列
                .limit(12)
                .collect(Collectors.toList());

        // 转换为VO , 这里不需要用service封装的转vo方法,因为这个方法会额外查询用户信息,但是我们这个接口不需要这个信息
        return sortedPictures.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    /**
     * 批量修改图片
     * 由于用户要处理的数量不大,这个版本的代码足够满足需求
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
     List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
     Long spaceId = pictureEditByBatchRequest.getSpaceId();
     String category = pictureEditByBatchRequest.getCategory();
     List<String> tags = pictureEditByBatchRequest.getTags();

     // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null ||CollectionUtils.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有空间权限");
        }

        // 3.查询指定图片,仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (CollectionUtils.isEmpty(pictureList)){
            return;
        }
        // 4.更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(tags);
            }
        });

        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);


        // 5.批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "名称解析错误");
        }
    }

    /**
     * 批量编辑图片分类和标签
     * 这个是优化版本:线程池 + 分批 + 并发 优化
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchEditPictureMetadata(PictureEditByBatchRequest request, User loginUser) {
        List<Long> pictureIdList = request.getPictureIdList();
        Long spaceId = request.getSpaceId();
        String category = request.getCategory();
        List<String> tags = request.getTags();

        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null ||CollectionUtils.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有空间权限");
        }

        // 查询空间下的图片
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR.getCode(), "指定的图片不存在或不属于该空间");
        }

        // 批量重命名
        String nameRule = request.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);

        // 分批处理避免长事务
        int batchSize = 100;
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));

            // 异步处理每批数据
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                batch.forEach(picture -> {
                    if (StrUtil.isNotBlank(category)){
                        picture.setCategory(category);
                    }
                    if (CollUtil.isNotEmpty(tags)){
                        picture.setTags(tags);
                    }
                });

                boolean result = this.updateBatchById(batch);
                if (!result) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "批量更新图片失败");
                }
            });

            futures.add(future);
        }

        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

    @Override
    public ImageOutPaintingResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        // 已经修改为,使用Sa-Token注解鉴权
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        ImageOutPaintingRequest.Input input = new ImageOutPaintingRequest.Input();
        input.setImageUrl(picture.getHost()+picture.getOriginalUrl());
        ImageOutPaintingRequest taskRequest = new ImageOutPaintingRequest();
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createImageScalingTask(taskRequest);
    }

}




